<!-- 视频播放器 webrtc -->
<template>
	<div class="videoBox">
		<div class="text">{{ viewTypeMap[props.viewType] }}</div>
		<!-- <video :id="'videoPlayer' + props.deviceCode" autoplay controls></video> -->
		<video ref="rtcVideo" autoplay controls></video>
	</div>
</template>

<script lang="ts" setup name="video-webrtc">
import { nextTick, onMounted, onUnmounted, ref } from 'vue';
import { JSWebrtc } from './jswebrtc.min.js';
import { getUrl } from '/@/utils/hm';
import { smokeStore } from '/@/stores/smoke';
import { useUserInfo } from '/@/stores/userInfo';

const props = defineProps({
	deviceCode: {
		type: String,
		default: '',
	},
	viewType: {
		type: String,
		default: 'live',
	},
});

const viewTypeMap: any = {
	live: '实时',
	review: '回看',
};

const rtcVideo = ref();

// const videoEl = ref(null);

onMounted(() => {
	// initVideo();
});

onUnmounted(() => {
	// TODO: 销户视频时，关闭视频流等操作
	closeVideo();
});

nextTick(() => {
	getVideo();
	initVideo();
});

const { playUrl, pushUrl } = getVideoUrl();

function initVideo() {
	new JSWebrtc.Player(playUrl, {
		video: rtcVideo.value,
		autoplay: true,
		onPlay: () => {
			console.log('start play');
		},
	});
}

// 查看视频
let continueTimer: any = null;
let wsConn = smokeStore().wsConn;
async function getVideo() {
	let params = {
		cmdType: 'getVideo',
		deviceCode: props.deviceCode,
		data: {
			url: pushUrl,
		},
	};
	wsConn.send(JSON.stringify(params));

	clearInterval(continueTimer);
	continueTimer = setInterval(() => {
		continueDevice();
	}, 15000);
}

function closeVideo() {
	let wsConn = smokeStore().wsConn;
	let params = {
		cmdType: 'closeVideo',
		deviceCode: props.deviceCode,
		data: {
			url: pushUrl,
		},
	};
	wsConn.send(JSON.stringify(params));
}

// 视频续时
function continueDevice() {
	let params = {
		cmdType: 'getVideo',
		deviceCode: props.deviceCode,
		data: null,
	};
	wsConn.send(JSON.stringify(params));
}

// 获取RTMP播放地址
function getVideoUrl() {
	let webrtcUrl = getUrl('webrtcUrl');
	let uid = useUserInfo().userInfos.id;

	let playUrl = '';
	let pushUrl = '';
	if (props.viewType == 'live') {
		playUrl = `webrtc://${webrtcUrl}:1985/live/${props.deviceCode}`;
		pushUrl = `rtmp://${webrtcUrl}:1984/live/${props.deviceCode}`;
	}

	if (props.viewType == 'review') {
		playUrl = `webrtc://${webrtcUrl}/review/${uid}/${props.deviceCode}`;
		pushUrl = `rtmp://${webrtcUrl}:1984/review/${uid}/${props.deviceCode}`;
	}

	return {
		playUrl,
		pushUrl,
	};
}
</script>

<style lang="scss" scoped>
.videoBox {
	position: relative;

	.text {
		position: absolute;
		right: 10px;
		top: 10px;
		padding: 5px 10px;
		border-radius: 3px;
		color: #67c23a;
		// background-color: #67c23a;
		border: 1px solid #67c23a;
		font-size: 12px;
	}

	video {
		width: 100%;
		aspect-ratio: 16/9;
		background-color: #333333;
	}
}
</style>
